import json

def createTable(sourceTable, outTable, featureCols):
    sqlStr = "CREATE TABLE {} AS SELECT {} FROM {}".format(outTable, ",".join(featureCols), sourceTable)
    flag = True
    msg = "success"
    try:
        plpy.execute(sqlStr)
    except Exception as e:
        msg = str(e) + " sql=" +sqlStr
        flag = False
    return flag, msg

def getTableMetaInfo(table_name):
    tmps = table_name.split(".")
    if len(tmps) > 0:
        table_name = tmps[1]
    sql_str = "select column_name, data_type from information_schema.columns where table_name = '%s'" %(table_name)
    rs = plpy.execute(sql_str)
    meta = {}
    for line in rs:
        meta[line['column_name']] = line['data_type']
    return meta

def logError(msg, status, result):
    result["status"] = status
    result["error_msg"] = msg
    return json.dumps(result)

def begin_alg(source_table, out_table, feature_cols):
    '''the result must be json string, the output_params key is needed.
        output_params include meta info for tables,
        each table must have out_table_name and output_cols
    '''
    result = {
        "status": 0,
        "error_msg": "success",
        "result": {
            "input_params": {
                "source_table": source_table,
                "out_table": out_table,
                "feature_cols": feature_cols,
            },
            "output_params": [
            ]
        }
    }
    featureCols = feature_cols.split(",")
    flag, msg = createTable(source_table, out_table, featureCols)
    if not flag:
        return logError(msg, 500, result)

    resultTable = {
        "out_table_name": out_table,
        "output_cols": featureCols
    }
    result["result"]["output_params"].append(resultTable)
    return json.dumps(result)